<template>
  <div>
    <!-- 角色操作界面 -->
    <div v-show="show">
      <!-- 查询表单 -->
      <div class="check-form-box">
        <el-form
          :inline="true"
          :model="searchModel.data"
          class="demo-form-inline"
        >
          <el-form-item label="角色名称">
            <el-input
              v-model.trim="searchModel.name"
              placeholder="请输入角色名称"
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchModel.state" placeholder="请选择状态">
              <el-option label="全部" :value="null" />
              <el-option label="禁用" value="0" />
              <el-option label="启用" value="1" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" color="#ea5b24" @click="searchRole()"
              >查询</el-button
            >
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              color="#ea5b24"
              @click="showDialog(0, null)"
              v-if="pinia.isShow[43]"
              >添加</el-button
            >
          </el-form-item>
        </el-form>
      </div>

      <!-- 列表 -->
      <div>
        <el-table :data="tableData.data" style="width: 100%">
          <el-table-column width="80" prop="id" label="ID" />
          <el-table-column prop="roleName" label="角色名称" />
          <el-table-column prop="roleDesc" label="角色描述" />
          <el-table-column prop="state" label="状态">
            <template #default="scope">
              {{
                scope.row.state == null
                  ? ""
                  : scope.row.state == 0
                  ? "禁用"
                  : "启用"
              }}
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="180">
            <template v-slot:default="scope">
              <div v-if="scope.row.id != 100">
                <el-button
                  link
                  type="primary"
                  size="small"
                  @click="showDialog(1, scope.row)"
                  v-if="pinia.isShow[46]"
                  >编辑</el-button
                >
                <el-button
                  link
                  type="primary"
                  size="small"
                  @click="disableRole(scope.row)"
                  v-if="pinia.isShow[45]"
                >
                  {{ scope.row.state == 1 ? "禁用" : "启用" }}</el-button
                >
                <el-button
                  link
                  type="primary"
                  size="small"
                  @click="authSetting(scope.row)"
                  v-if="pinia.isShow[44]"
                  >授权设置</el-button
                >
              </div>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页插件 -->
        <div style="text-align: center">
          <el-pagination
            :total="totalNum"
            @current-change="handleCurrentChange"
            background
            :page-size="size"
            layout="prev, pager, next, total"
            :current-page="page"
          />
        </div>
      </div>

      <!--添加/编辑管理员表单 -->
      <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        center="true"
        modal="true"
        width="25%"
      >
        <el-form :model="roleModel" :rules="rules" ref="ruleFormRef">
          <el-form-item label="id" v-if="false">
            <el-input v-model.trim="roleModel.id" autocomplete="off" />
          </el-form-item>
          <el-form-item
            label="角色名称"
            prop="roleName"
            :label-width="editFormLabelWidth"
          >
            <el-input v-model.trim="roleModel.roleName" autocomplete="off" />
          </el-form-item>
          <el-form-item label="角色描述" :label-width="editFormLabelWidth">
            <el-input v-model.trim="roleModel.roleDesc" autocomplete="off" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button
              type="primary"
              @click="formSubmit(ruleFormRef)"
              color="#ea5b24"
              >确定</el-button
            >
          </span>
        </template>
      </el-dialog>
    </div>
    <!-- 权限设置界面 -->
    <div v-if="!show">
      <!-- <tree :adminId="adminId"></tree> -->
      <power :adminId="adminId"></power>
      <el-button type="primary" color="#ea5b24" @click="back">返回</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox, FormInstance, FormRules } from "element-plus";
import { onMounted, reactive, ref } from "vue";
import { addRoleApi, editRoleApi, roleFindApi } from "../../../api/index";
// import tree from "./tree.vue"
import power from "./power.vue";
import { usePermissStore } from "../../../store/permiss";
const pinia = usePermissStore();

const editFormLabelWidth = "80px";
let tableData: any = reactive([]);
const totalNum = ref(0);
const page = ref(1);
const size = 8;

//表单校验
const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules>({
  roleName: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
});

const searchModel: any = reactive({
  name: null,
  state: null,
  page: page,
  size: size,
});
// 控制添加/编辑对话框
const dialogVisible = ref(false);
const dialogTitle = ref("");
const dialogType = ref(0);
const roleModel: any = reactive({
  id: 0,
  roleName: "",
  roleDesc: "",
});

// 控制添加/编辑dialog显示
const showDialog = (type: number, row) => {
  dialogVisible.value = true;
  dialogType.value = type;
  ruleFormRef.value ? ruleFormRef.value.clearValidate() : false;
  if (type === 0) {
    dialogTitle.value = "添加角色";
    Object.keys(roleModel).forEach((key) => (roleModel[key] = null));
  } else {
    dialogTitle.value = "编辑角色";
    roleModel.id = row.id;
    roleModel.roleName = row.roleName;
    roleModel.roleDesc = row.roleDesc;
  }
};

// 翻页
let flipData = reactive({
  page: page,
  size: size,
});
const handleCurrentChange = (val: number) => {
  page.value = val;
  flipData.page = page.value;
  findRole(flipData);
};

// 搜索提现订单
const searchRole = () => {
  page.value = 1;
  searchParmSearch();
  findRole(searchModel);
  flipData = JSON.parse(JSON.stringify(searchModel));
};

// 搜索参数检查
const searchParmSearch = () => {
  Object.keys(searchModel).forEach((key) => {
    if (!searchModel[key]) {
      searchModel[key] = null;
    }
  });
};

// 查询角色
const findRole = (searchModel) => {
  roleFindApi(searchModel).then((res) => {
    if (res.data.code === 2000) {
      tableData.data = res.data.data.data;
      totalNum.value = res.data.data.total;
    } else {
      ElMessage.error("查询失败");
    }
  });
};
// 添加/编辑角色表单提交
const formSubmit = (formEl) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      if (dialogType.value === 0) {
        addRoleApi(roleModel).then((res) => {
          if (res.data.code === 2000) {
            ElMessage({
              message: "添加成功.",
              type: "success",
            });
            findRole(searchModel);
          } else {
            ElMessage.error("添加失败");
          }
        });
      } else {
        roleModel.menus = null;
        editRoleApi(roleModel).then((res) => {
          if (res.data.code === 2000) {
            ElMessage({
              message: "编辑成功.",
              type: "success",
            });
            findRole(searchModel);
          } else {
            ElMessage.error("编辑失败");
          }
        });
      }
      dialogVisible.value = false;
    } else {
      return false;
    }
  });
};

// 禁用角色
const disableRole = (row) => {
  ElMessageBox.confirm(
    `是否确认${row.state == 1 ? "禁用" : "启用"}该角色?`,
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  ).then(() => {
    editRoleApi({
      id: row.id,
      state: row.state == 1 ? "0" : "1",
      menus: row.state == 1 ? [] : null,
      admins: row.state == 1 ? [] : null,
    }).then((res) => {
      if (res.data.code === 2000) {
        ElMessage({
          message: "成功.",
          type: "success",
        });
        findRole(searchModel);
      } else {
        ElMessage.error("失败");
      }
    });
  });
};

// 角色操作组件是否显示
const show = ref(true);

//选中角色id
let adminId = ref(0);
// 授权设置
const authSetting = (row) => {
  adminId.value = row.id;
  show.value = false;
};
// 返回角色操作
const back = () => {
  show.value = !show.value;
};
interface Option {
  key: number;
  label: string;
  disabled: boolean;
}

const generateData = () => {
  const data: Option[] = [];
  for (let i = 1; i <= 15; i++) {
    data.push({
      key: i,
      label: `Option ${i}`,
      disabled: i % 4 === 0,
    });
  }
  return data;
};

const data = ref<Option[]>(generateData());
const value = ref([]);

onMounted(() => {
  findRole(searchModel);
});
</script>

<style lang="less" scoped>
.transferTreeBox {
  display: flex;
  width: 590px;
  justify-content: space-around;

  .SelectBox {
    border: 1px solid #ccc;
    height: 270px;
    width: 200px;
    color: #fff;
    position: relative;

    .boxTitle {
      background: #a0cfff;
      height: 30px;
      line-height: 30px;
      text-align: center;
      border-bottom: 1px solid #ccc;
      cursor: pointer;
    }

    .boxCenter {
      height: 100%;
      width: 100%;
      max-height: 239px;
      overflow-y: scroll;
    }
  }

  .transferBtn {
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    .pickBtn {
      height: 30px;
      width: 50px;
      background: #a0cfff;
      color: #fff;
      font-weight: 700;
      font-size: 20px;
      border-radius: 5px;
      margin-top: 10px;
      text-align: center;
      line-height: 30px;
      cursor: pointer;
    }
  }
}
</style>
